import { FC, useEffect, useState } from "react";

// 引入资源

import type { CheckboxProps } from 'antd';
import { Button, message, Popconfirm } from 'antd';
import styles from './styles.module.scss'
import { Breadcrumb } from "antd";
import { Link } from "react-router-dom";
// 引入请求
import { reqCartList, reqGuessLike, reqCartListAllSelect, reqUpdateCartList, reqDeleteGoods } from "../../api/CartList";
// 引入类型
import { CartListData, guessLikeGoods } from "../../api/CartList/type";
const CartList: FC = () => {


    //商品选择逻辑
    // 新增选中状态
    const [selectedIds, setSelectedIds] = useState<string[]>([]);

    // 修改全选处理逻辑
    const onChange: CheckboxProps['onChange'] = (e) => {
        if (e.target.checked) {
            setSelectedIds(cartListGoods.map(item => item.skuId));
            getCartListAllSelect()
        } else {
            setSelectedIds([]);
            getCartListAllSelect()
        }
    };

    // 新增单个商品勾选处理
    const handleSingleCheck = (skuId: string, checked: boolean, count: number) => {
        setSelectedIds(prev => checked ? [...prev, skuId] : prev.filter(id => id !== skuId));
        reqUpdateCartList({
            selected: checked,
            count
        }, skuId).then((res) => {
            console.log('修改购物车商品', res)
        })

    };
    //购物车全选/取消
    const getCartListAllSelect = () => {
        reqCartListAllSelect({
            selected: selectedIds.length === cartListGoods.length && cartListGoods.length > 0,
            ids: selectedIds,
        }).then((res) => {
            console.log('全选/取消购物车商品', res)
        })
    }

    useEffect(() => {
        console.log('已选商品ids', selectedIds)

        return () => {

        }
    }, [selectedIds])

    // 商品数量改变
    // 修改商品数量处理方法
    const handleSingleCount = async (skuId: string, checked: boolean, newCount: number) => {
        if (newCount < 1) return;

        // 保存原始数据用于回滚
        const originalGoods = [...cartListGoods];

        try {
            // 立即更新本地状态（乐观更新）
            setCartListGoods(prev =>
                prev.map(item =>
                    item.skuId === skuId ? { ...item, count: newCount } : item
                )
            );

            // 发送更新请求
            await reqUpdateCartList({
                selected: checked,
                count: newCount
            }, skuId);

            // 二次验证确保数据一致性
            await getCartList();

        } catch (error) {
            console.error('修改失败:', error);
            // 请求失败时回滚状态
            setCartListGoods(originalGoods);
            // 可以添加错误提示（需要引入消息组件）
            // message.error('更新失败，请重试');
        }
    };


    //删除单个商品
    const handleDelete = async (id: string) => {

        try {
            await reqDeleteGoods({
                ids: [id]
            }).then((res) => {
                console.log('删除单个商品', res)
            })
            await getCartList();
            message.success('删除成功！');

        } catch (error) {
            console.error('删除失败:', error);
            message.error('删除失败！');
        }
    }
    //批量删除
    const handleBatchDelete = async () => {

        try {
            await reqDeleteGoods({
                ids: selectedIds
            }).then((res) => {
                console.log('批量删除商品', res)
            })
            await getCartList();
            message.success('删除成功！');

        } catch (error) {
            console.error('删除失败:', error);
            message.error('删除失败！');
        }
    }






    const [cartListGoods, setCartListGoods] = useState<CartListData[]>([])
    // 获取购物车列表
    const getCartList = () => {
        reqCartList().then((res) => {
            setCartListGoods(res.result)
        })
    }


    useEffect(() => {
        getCartList()

        return () => {

        }
    }, [])


    // 猜你喜欢
    const [guessLikeGoods, setGuessLikeGoods] = useState<guessLikeGoods[]>()
    const getGuessLike = () => {
        reqGuessLike().then((res) => {
            setGuessLikeGoods(res.result)
        })
    }
    useEffect(() => {
        getGuessLike()
        return () => {

        }
    }, [])

    return (
        <div className={styles.cartList}>
            {/* 面包屑 */}
            <div className={styles.bread}>
                <Breadcrumb
                    items={[
                        {
                            title: <Link to={'/home'}>首页</Link>,
                        },
                        {
                            title: <span > 购物车</span>
                        },
                    ]}
                />
            </div>
            {/* 购物车列表 */}
            <div className={styles.cartBoxs}>
                {/* 表头 */}
                <div className={styles.listHeader}>
                    <span>
                        <input
                            type="checkbox"
                            onChange={onChange}
                            checked={selectedIds.length === cartListGoods.length && cartListGoods.length > 0}
                        />
                        全选
                    </span>
                    <span>商品信息</span>
                    <span>单价</span>
                    <span>数量</span>
                    <span>小计</span>
                    <span>操作</span>
                </div>
                {/* 商品信息 */}
                {cartListGoods.map((good) => {
                    return (<div className={styles.cartGood} key={good.skuId}>
                        <span>
                            <input
                                type="checkbox"
                                onChange={(e) => handleSingleCheck(good.skuId, e.target.checked, good.count)}
                                checked={selectedIds.includes(good.skuId)}
                            />
                        </span>
                        <div className={styles.goodInfo}>
                            <img src={good.picture} />
                            <span>{good.name}</span>
                            <span>{good.attrsText}</span>
                        </div>
                        <div className={styles.price}>
                            {good.price}￥
                        </div>

                        <div className={styles.count}>
                            <span onClick={() => {
                                handleSingleCount(
                                    good.skuId,
                                    selectedIds.includes(good.skuId),
                                    Math.max(good.count - 1, 1)
                                )
                            }}>-</span>
                            <span>{good.count}</span>
                            <span onClick={() => {
                                handleSingleCount(
                                    good.skuId,
                                    selectedIds.includes(good.skuId),
                                    good.count + 1
                                )
                            }}>+</span>
                        </div>
                        <div className={styles.total}>
                            {parseInt(good.price) * good.count}￥
                        </div>
                        <div className={styles.action} >
                            <Popconfirm
                                title="确定要删除吗？"
                                onConfirm={() => {
                                    handleDelete(good.skuId)
                                }}
                                onCancel={() => {
                                    return
                                }}
                                okText="确定"
                                cancelText="取消"
                            >
                                <Button danger>删除</Button>
                            </Popconfirm>
                        </div>
                    </div>)
                })}



            </div>
            {/* 购物车功能 */}
            <div className={styles.cartFeatures}>
                <div className={styles.left}>
                    <label>
                        <input
                            type="checkbox"
                            onChange={onChange}
                            checked={selectedIds.length === cartListGoods.length && cartListGoods.length > 0}
                        />
                        全选
                    </label>

                    {/* 修改点：将嵌套的<a>替换为<span> */}
                    <Popconfirm
                        title="确定要删除吗？"
                        onConfirm={handleBatchDelete}
                        okText="确定"
                        cancelText="取消"
                    >
                        <span className={styles.deleteBtn}>批量删除</span>
                    </Popconfirm>

                    {/* 其他链接也需要检查 */}
                    <span className={styles.actionLink}>移入收藏夹</span>
                    <span className={styles.actionLink}>清空失效商品</span>
                </div>
                <div className={styles.right}>
                    <span>共 <em>{cartListGoods.length}</em> 件商品，已选择 <em>{selectedIds.length}</em> 件，商品合计：
                        <em>¥{cartListGoods
                            .filter(item => selectedIds.includes(item.skuId))
                            .reduce((sum, item) => sum + (parseInt(item.price) * item.count), 0)}
                        </em>
                    </span>
                    <button disabled={selectedIds.length === 0}>下单结算</button>
                </div>
            </div>
            {/* 猜你喜欢 */}
            <div className={styles.guessLike}>
                <div className={styles.title}>
                    <h3>猜你喜欢</h3>
                </div>
                <div className={styles.goodsList}>
                    {guessLikeGoods?.map((item) => {
                        return (
                            <div className={styles.goodItem} key={item.id}>
                                <img src={item.picture} alt="" />
                                <p className={styles.name}>{item.name}</p>
                                <p className={styles.desc}>{item.desc}</p>
                                <p className={styles.price}>{item.price}</p>
                            </div>
                        )
                    })}


                </div>
            </div>
        </div>
    )
}

export default CartList